﻿using Coolzon.Common;
using Coolzon.UI.Common.Event.Web;
using Coolzon.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using RT = Coolzon.Metadata.Runtime;

namespace Coolzon.UI.Common.WebProxies
{
    public class WebProxy
    {
        public static WebProxy Instance = new WebProxy();


        public ServiceResult<List<RT.SolutionFile>> GetSolutionFileList(string solution, string localVersion)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(WebEventProxy.Instance.BaseUrl);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                try
                {
                    return httpClient.GetAsync(string.Format("api/solution/filelist?solution={0}&localVersion={1}", solution, localVersion)).Result.Content.ReadAsAsync<ServiceResult<List<RT.SolutionFile>>>().Result;
                }
                catch (Exception ex)
                {
                    return new ServiceResult<List<RT.SolutionFile>>(false, 1, ex.Message);
                }
            }
        }

        public Web.Models.DataResult GetDataResult(LoadDataParam param)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(WebEventProxy.Instance.BaseUrl);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                try
                {
                    ServiceResult<Web.Models.DataResult> result = httpClient.PostAsJsonAsync<LoadDataParam>("api/data/load", param)
                        .Result.Content.ReadAsAsync<ServiceResult<Web.Models.DataResult>>().Result;
                    if (result.IsSuccess)
                    {
                        return result.Data;
                    }
                    return null;
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
        }

        public List<Web.Models.Library> GetLibraries()
        {
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(WebEventProxy.Instance.BaseUrl);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                try
                {
                    return httpClient.GetAsync("api/library/list").Result.Content.ReadAsAsync<ServiceResult<List<Web.Models.Library>>>().Result.Data;
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
        }
    }
}
